package com.redisdemo.File;

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * <h3>redisDemo</h3>
 * <p>复制文件覆盖模式</p>
 *
 * @author gdw
 * @since 2024-07-02 15:50:19
 */
public class FileCopyTask implements Runnable{
    private final String sourceFilePath;
    private final String destFilePath;
    private final long start;
    private final long size;

    public FileCopyTask(String sourceFilePath, String destFilePath, long start, long size) {
        this.sourceFilePath = sourceFilePath;
        this.destFilePath = destFilePath;
        this.start = start;
        this.size = size;
    }
    @Override
    public void run() {
        try (RandomAccessFile sourceFile = new RandomAccessFile(sourceFilePath, "r");
             FileChannel sourceChannel = sourceFile.getChannel();
             RandomAccessFile destFile = new RandomAccessFile(destFilePath, "rw");
             FileChannel destChannel = destFile.getChannel()) {

            MappedByteBuffer sourceBuffer = sourceChannel.map(FileChannel.MapMode.READ_ONLY, start, size);
            MappedByteBuffer destBuffer = destChannel.map(FileChannel.MapMode.READ_WRITE, start, size);

            byte[] bytes = new byte[(int) size];
            sourceBuffer.get(bytes);
            destBuffer.put(bytes);

            System.out.println(Thread.currentThread().getName() + ": Copied " + size + " bytes from " + start);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
